/*
 * Copyright (c) 2006-2020, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2020-11-04     Ghazigq       the first version
 */
#include <board.h>
#include <rtthread.h>
#include <rtdevice.h>

#ifdef RT_USING_WDT

//#define DRV_DEBUG
#define LOG_TAG             "drv.wdt"
#include <drv_log.h>

struct nrf_wdt_obj
{
    nrfx_wdt_channel_id wdt_chl_id;
    rt_uint16_t is_start;
};
static struct nrf_wdt_obj nrf_wdt;
static struct rt_watchdog_ops ops;
static rt_watchdog_t watchdog;
static nrfx_wdt_config_t default_config = NRFX_WDT_DEAFULT_CONFIG;

static void wdt_event_handler(void)
{
    LOG_D("wdt event!");
}

static rt_err_t wdt_init(rt_watchdog_t *wdt)
{
    return RT_EOK;
}

static rt_err_t wdt_control(rt_watchdog_t *wdt, int cmd, void *arg)
{
    switch (cmd)
    {
        /* feed the watchdog */
    case RT_DEVICE_CTRL_WDT_KEEPALIVE:
        nrfx_wdt_channel_feed(nrf_wdt.wdt_chl_id);
        break;
        /* set watchdog timeout */
    case RT_DEVICE_CTRL_WDT_SET_TIMEOUT:
        default_config.reload_value = (*((rt_uint32_t*)arg));
        if(nrf_wdt.is_start)
            return -RT_ERROR;
        break;
    case RT_DEVICE_CTRL_WDT_START:
        nrfx_wdt_init(&default_config, wdt_event_handler);
        nrfx_wdt_channel_alloc(&nrf_wdt.wdt_chl_id);
        nrf_wdt.is_start = 1;
        nrfx_wdt_enable();
        break;
    default:
        LOG_W("This command is not supported.");
        return -RT_ERROR;
    }
    return RT_EOK;
}

int rt_wdt_init(void)
{
    nrf_wdt.is_start = 0;

    ops.init = &wdt_init;
    ops.control = &wdt_control;
    watchdog.ops = &ops;
    /* register watchdog device */
    if (rt_hw_watchdog_register(&watchdog, "wdt", RT_DEVICE_FLAG_DEACTIVATE, RT_NULL) != RT_EOK)
    {
        LOG_E("wdt device register failed.");
        return -RT_ERROR;
    }
    LOG_D("wdt device register success.");
    return RT_EOK;
}
INIT_BOARD_EXPORT(rt_wdt_init);

#endif /* RT_USING_WDT */
